/**
 * @Project： Lqyd_Android
 * @Title：BoutiquePage
 * @Description：
 * @Author：wayne
 * @Date：2014年8月11日上午10:42:19
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.http.Req.QryKnowledgeDocumentListEty;
import com.image_see.ImageSeeActivity;
import com.mywork.activity.PdfWebActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.OrderMenuMyCouponActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.widget.slideview.ListViewCompat;
import com.shwread.android.ui.widget.slideview.SlideView;
import com.shwread.android.ui.widget.slideview.SlideView.OnSlideListener;
import com.shwread.http.base.EmptyHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryMsgsByPositionAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.MessageBean;
import logic.bean.MessageInfo;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.Util;


/**
 * @Project： Lqyd_Android
 * @Title：BoutiquePage
 * @Description：消息中心页面
 * @Author：wayne
 * @Date：2014年8月11日上午10:42:19
 */
public class MessagePage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        OnItemClickListener,
        OnSlideListener {
    /**
     * 企业消息默认页数
     */
    private static int DEFAULT_PAGENUM_E = 1;
    /**
     * 系统消息默认页数
     */
    private static int DEFAULT_PAGENUM_S = 1;
    /**
     * 企业消息未读总条数
     */
    private static Integer UNREAD_MESSAGE_COUNT_E = null;
    /**
     * 系统消息未读总条数
     */
    private static Integer UNREAD_MESSAGE_COUNT_S = null;
    private static int DEFAULT_PAGELENGTH = 2000;

    private TextView tvTitle, leftText, leftCount, rightText, rightCount;
    //	private ImageView             ivPersion;
    private Button ivBack;
    private View leftView, rightView, emptyView, bodyView, msgLayouView;
    private List<MessageInfo> enterpriseMessage, systemMessage, messages;
    private Adapter adapter;
    /**
     * true:当前为企业消息页面，false:当前为系统消息页面
     */
    private static boolean isEnterprise = true;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    /**
     * 标示第一次进来数据是否加载完成
     */
    private Boolean isLoadEnterprise = null, isLoadSystem = null;
    /**
     * 判断最后一次数据加载是否成功，不成功的话每次进入此页面需要显示加载动画
     */
//	private boolean            isLastSuccess          = false;
    private static MessagePage instance;

    private ListViewCompat lv;
    private SlideView mLastSlideViewWithStatusOn;

    public static MessagePage getInstance(MainActivity t) {
        if (instance == null) instance = new MessagePage(t);
        return instance;
    }

    public MessagePage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;

        curMyView = bActivity.getLayoutInflater().inflate(R.layout.message_lay, null);
//		isEnterprise = true;
        initView();
        setListener();
        return curMyView;
    }

    void initView() {
        enterpriseMessage = new ArrayList<MessageInfo>();
        systemMessage = new ArrayList<MessageInfo>();
        messages = new ArrayList<MessageInfo>();
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(bActivity.getResources().getString(R.string.maintab_message));
        //		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        //		ivPersion.setVisibility(View.VISIBLE);
        ivBack = (Button) curMyView.findViewById(R.id.common_header_back);
        ivBack.setVisibility(View.VISIBLE);
        lv = (ListViewCompat) curMyView.findViewById(R.id.message_listview);
        msgLayouView = curMyView.findViewById(R.id.message_layout);
        loadingView = curMyView.findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);

        leftText = (TextView) curMyView.findViewById(R.id.message_top_left_text);
        leftCount = (TextView) curMyView.findViewById(R.id.message_top_left_count);
        rightText = (TextView) curMyView.findViewById(R.id.message_top_right_text);
        rightCount = (TextView) curMyView.findViewById(R.id.message_top_right_count);
        leftView = curMyView.findViewById(R.id.message_top_left);
        rightView = curMyView.findViewById(R.id.message_top_right);
        bodyView = curMyView.findViewById(R.id.message_body);
        emptyView = curMyView.findViewById(R.id.message_body_empty);
    }

    void setListener() {
        //		ivPersion.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        leftView.setOnClickListener(this);
        rightView.setOnClickListener(this);

        adapter = new Adapter();
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
    }

    private class Adapter
            extends
            BaseAdapter {

        private LayoutInflater mInflater;

        Adapter() {
            mInflater = bActivity.getLayoutInflater();
        }

        List<MessageInfo> currData = new ArrayList<MessageInfo>();

        public void setCurrData(List<MessageInfo> currData) {
            this.currData = currData;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return currData.size();
        }

        @Override
        public Object getItem(int arg0) {
            return currData.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int position, View view, ViewGroup arg2) {
            ViewHolder holder;
            SlideView slideView = (SlideView) view;
            if (slideView == null) {
                View itemView = mInflater.inflate(R.layout.list_item, null);

                slideView = new SlideView(bActivity);
                slideView.setContentView(itemView);

                holder = new ViewHolder(slideView);
                slideView.setOnSlideListener(MessagePage.this);
                slideView.setTag(holder);
            } else {
                holder = (ViewHolder) slideView.getTag();
            }
            final MessageInfo info = currData.get(position);
            info.setSlideView(slideView);
            info.getSlideView().shrink();
            if (info.getWriteSource().equals("1")) {//企业
                holder.img.setImageResource(R.drawable.message_ent);
//				GlideUtil.load(context, info.getMsgImgUrl(), R.drawable.message_ent, holder.img);
            } else {
                holder.img.setImageResource(R.drawable.message_sys);
//				GlideUtil.load(context, info.getMsgImgUrl(), R.drawable.message_sys, holder.img);
            }
            holder.unreadImg.setVisibility(info.getIsRead().toLowerCase().equals("n") ? View.VISIBLE : View.GONE);
            if (info.getIsRead().toLowerCase().equals("n")) {//未读
                holder.list_item_par.setBackgroundColor(Color.parseColor("#ffffff"));
            } else {
                holder.list_item_par.setBackgroundColor(Color.parseColor("#f8f8f8"));
            }
            holder.title.setText(info.getTitle());
            holder.time.setText(DateUtil.getShortTime(info.getSendStartTime()));
            holder.content.setText(info.getShortMsg());
            holder.deleteHolder.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    delMsg(info);
                    //					System.out.println("当前要删除的position:"+position);
                    //					System.out.println("删除前的数据:"+currData.size()+","+currData.toString());
                    currData.remove(position);
                    //					System.out.println("删除后的数据:"+currData.size()+","+currData.toString());
                    notifyDataSetChanged();
                    messages = currData;
                }
            });
            return slideView;
        }
    }

    private final class ViewHolder {
        ImageView img;
        ImageView unreadImg;
        TextView title, time, content;
        View deleteHolder;
        RelativeLayout list_item_par;

        ViewHolder(View view) {
            img = (ImageView) view.findViewById(R.id.message_item_img);
            unreadImg = (ImageView) view.findViewById(R.id.message_item_img_flag);
            title = (TextView) view.findViewById(R.id.message_item_title);
            content = (TextView) view.findViewById(R.id.message_item_content);
            time = (TextView) view.findViewById(R.id.message_item_time);
            deleteHolder = view.findViewById(R.id.delete);
            list_item_par = (RelativeLayout) view.findViewById(R.id.list_item_par);
        }
    }

    @Override
    public int enter(IUIPage<?> arg0) {
//		if (!isLastSuccess)
//		{
        updateLoadingView(0);
//		}
        initData();
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.MESSAGE_REFRESH_CODE:
            case DefaultConsts.PAGE_ONRESUME_CODE:
                System.out.println("收到数据刷新通知！！！");
                initData();
                break;
        }
    }

//	private int num = 0;

    private void initData() {
//		if (num <= 0)
//		{
//			num = 4;
        //获取未读消息总条数
//			new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
//			new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
        //获取消息数据
//			new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, DEFAULT_PAGENUM_E, DEFAULT_PAGELENGTH, new GetMsgAction(true)).start();
//			new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, DEFAULT_PAGENUM_S, DEFAULT_PAGELENGTH, new GetMsgAction(false)).start();
        new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ALL, DEFAULT_PAGENUM_S, DEFAULT_PAGELENGTH, new GetMsgAction()).start();
//		}
    }


    private void delMsg(MessageInfo info) {
        NewActionHelp.delMsgBySendId(bActivity, String.valueOf(info.getMsgViewId()), new EmptyHttpResponseHandler());
    }

    private MessageInfo readMsg(int position, MessageInfo info) {
        if (info.getIsRead().toLowerCase().equals("n")) {
            NewActionHelp.readMsgBySendId(bActivity, String.valueOf(info.getMsgViewId()), new EmptyHttpResponseHandler());

            info.setIsRead("y");
            messages.set(position, info);
            adapter.setCurrData(messages);
        }
//		messageUnReadChange();
        return info;
    }

    /**
     * 请求下一页数据（分页）
     */
    private void getNextPageData() {
        String source = DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE;
        int pageNum = 1;
        if (isEnterprise) {
            ++DEFAULT_PAGENUM_E;
            pageNum = DEFAULT_PAGENUM_E;
        } else {
            source = DefaultConsts.TYPE_WRITESOURCE_SYSTEM;
            ++DEFAULT_PAGENUM_S;
            pageNum = DEFAULT_PAGENUM_S;
        }
        new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, source, pageNum, DEFAULT_PAGELENGTH, new GetMsgAction()).start();
    }

    private class GetMsgAction
            extends
            BaseAction {

        @Override
        protected void onError() {
            Log.e("加载失败了","消息加载失败");
            super.onError();
        }

        @Override
        public void OK(Object obj) {
            final MessageBean msg = (MessageBean) obj;
            messages = msg.getColumns();
            if (messages == null || messages.size() == 0) {
                bActivity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        msgLayouView.setVisibility(View.VISIBLE);
                        emptyView.setVisibility(View.VISIBLE);
                        loadingView.setVisibility(View.GONE);
                    }
                });
                return;
            }
            new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getId());
                    bActivity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            loadingView.setVisibility(View.GONE);
                            msgLayouView.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                            adapter.setCurrData(messages);
                        }
                    });
                }

            }).start();
//			updateUI();
        }
    }


    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                bActivity.finish();
                break;
            default:
                break;
        }
    }

    void doMessageDetail(MessageInfo info) {
        if (Util.isNotEmpty(info.getAddressUrl())) {
            switch (info.getMsgType()) {
                case 101://图片查看
                    Intent extras = new Intent();
                    extras.setClass(context, ImageSeeActivity.class);
                    ArrayList<String> urlList = new ArrayList<>();
                    String url =  info.getAddressUrl();
                    String[] split = url.split(",");
                    Collections.addAll(urlList, split);
                    extras.putStringArrayListExtra("urlList", urlList);
                    bActivity.startActivity(extras);
                    break;
                case 102://pdf查看
                    Intent intent = new Intent();
                    intent.setClass(context, PdfWebActivity.class);
                    QryKnowledgeDocumentListEty qryKnowledgeDocumentListEty = new QryKnowledgeDocumentListEty(info.getTitle(), info.getAddressUrl(), (int)info.getBookId(), 0);
                    intent.putExtra("QryKnowledgeDocumentListEty", qryKnowledgeDocumentListEty);
                    bActivity.startActivity(intent);
                    break;
                default:
                    bActivity.goWebViewActivity(info);
                    break;
            }
        } else {
            switch (info.getMsgType()) {
                case MessageInfo.TYPE_SYSTEM:
                    bActivity.goSystemNotiActivity(info);
                    break;
                case MessageInfo.TYPE_BOOK:
                    bActivity.goBookDetailActivity(info.getBooks());
                    break;
                case MessageInfo.TYPE_LIVES:
                case MessageInfo.TYPE_URL:
                    bActivity.goWebViewActivity(info);
                    break;
                case MessageInfo.TYPE_ORDER:
//					bActivity.startActivity(new Intent(bActivity, MyAppointmentListActivity.class));
                    break;
                case MessageInfo.TYPE_COUPON:
                    bActivity.startActivity(new Intent(bActivity, OrderMenuMyCouponActivity.class));
                    break;
                case MessageInfo.TYPE_QINGJIA:// 请假提醒
                    bActivity.goResMoreActivity("请假管理");
                    //notificationIntent.setClass(context, ResMoreActivity.class);
                    //notificationIntent.putExtra("title", "请假管理");
                    //notificationIntent.putExtra("push", true);
                    break;
                case MessageInfo.TYPE_CHUCAI:// 出差提醒
                    bActivity.goResMoreActivity("出差管理");
                    //notificationIntent.setClass(context, ResMoreActivity.class);
                    //notificationIntent.putExtra("title", "出差管理");
                    //notificationIntent.putExtra("push", true);
                    break;
                case MessageInfo.TYPE_JIABAN:// 加班提醒
                    bActivity.goResMoreActivity("加班管理");
                    //notificationIntent.setClass(context, ResMoreActivity.class);
                    //notificationIntent.putExtra("title", "加班管理");
                    //notificationIntent.putExtra("push", true);
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                msgLayouView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.round_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingView.setVisibility(View.GONE);
                msgLayouView.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//		final MessageInfo info = isEnterprise ? enterpriseMessage.get(position) : systemMessage.get(position);
        final MessageInfo info = messages.get(position);
        doMessageDetail(readMsg(position, info));
    }

    @Override
    public void onSlide(View view, int status) {
        if (mLastSlideViewWithStatusOn != null && mLastSlideViewWithStatusOn != view) {
            mLastSlideViewWithStatusOn.shrink();
        }

        if (status == SLIDE_STATUS_ON) {
            mLastSlideViewWithStatusOn = (SlideView) view;
        }
    }
}
